package com.customization.cronjob;

import com.alibaba.fastjson.JSONObject;
import com.customization.commons.Console;
import com.engine.kq.bean.ImportSetting;
import com.engine.kq.biz.KQFormatBiz;
import com.engine.kq.timer.KQQueue;
import com.engine.kq.timer.KQTaskBean;
import com.engine.kq.wfset.util.SplitActionUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import weaver.common.DateUtil;
import weaver.common.StringUtil;
import weaver.conn.BatchRecordSet;
import weaver.conn.RecordSet;
import weaver.file.Prop;
import weaver.general.BaseBean;
import weaver.general.StaticObj;
import weaver.general.Util;
import weaver.hrm.common.Tools;
import weaver.interfaces.datasource.DataSource;
import weaver.interfaces.schedule.BaseCronJob;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class KQScheduleSignImportFromNewCapec extends BaseCronJob {


    private String beforeDay = "1";

    private String pickUpField = "";

    private String pickUpTablename = "";

    public String getPickUpTablename() {
        return pickUpTablename;
    }

    public void setPickUpTablename(String pickUpTablename) {
        this.pickUpTablename = pickUpTablename;
    }

    public String getBeforeDay() {
        return beforeDay;
    }

    public void setBeforeDay(String beforeDay) {
        this.beforeDay = beforeDay;
    }

    public String getPickUpField() {
        return pickUpField;
    }

    public void setPickUpField(String pickUpField) {
        this.pickUpField = pickUpField;
    }

    public void execute() {
        RecordSet var1 = new RecordSet();
        try {
            var1.writeLog("begin do KQScheduleSignImportJob invoke ...");
            Prop.getInstance();
            int var3 = Util.getIntValue(this.beforeDay, 1);
            this.importData(Tools.getDate(Tools.getToday(), -var3), Tools.getDate(Tools.getToday()), false);
        } catch (Exception var6) {
            var1.writeLog(var6);
        }

    }


    private void importData(String beginDate, String endDate, boolean isSyn) throws Exception {
        RecordSet rs = new RecordSet();
        String sql = "";
        endDate = Tools.getDate(endDate, 1);
        BatchRecordSet bRs = new BatchRecordSet();
        List<List<Object>> lsParams = new ArrayList<>();
        List<Object> params = null;

        List<List<Object>> lsDelParams = new ArrayList<>();
        List<Object> delParams = null;

        List<String> lsFormatData = new ArrayList<>();
        List<List<Object>> lsFormatParams = new ArrayList<>();
        List<Object> formatParams = null;

        Map<String, Map<String, String>> users = getUsers(7);
        Map<String, String> loginidMap = users.get("loginidMap");
        Map<String, String> lastnameMap = users.get("lastnameMap");
        Map<String, String> workcodeMap = users.get("workcodeMap");
        List<String> keymap = new ArrayList<>();


        List<ImportSetting> lsImportSetting = new ArrayList<>();
        ImportSetting importSetting = null;
        sql = " select datasourceid, loginid, workcode, lastname, signdate, signtime, tablename, clientaddress,longitude,latitude,addr,memo " +
                " from HrmScheduleSignSet ";
        rs.execute(sql);
        while (rs.next()) {
            importSetting = new ImportSetting();
            importSetting.setDatasourceid(Util.null2String(rs.getString("datasourceid")).trim());
            importSetting.setLoginid(Util.null2String(rs.getString("loginid")).trim());
            importSetting.setWorkcode(Util.null2String(rs.getString("workcode")).trim());
            importSetting.setLastname(Util.null2String(rs.getString("lastname")).trim());
            importSetting.setSigndate(Util.null2String(rs.getString("signdate")).trim());
            importSetting.setSigntime(Util.null2String(rs.getString("signtime")).trim());
            importSetting.setTablename(Util.null2String(rs.getString("tablename")).trim());
            importSetting.setClientaddress(Util.null2String(rs.getString("clientaddress")).trim());
            importSetting.setLongitude(Util.null2String(rs.getString("longitude")).trim());
            importSetting.setLatitude(Util.null2String(rs.getString("latitude")).trim());
            importSetting.setAddr(Util.null2String(rs.getString("addr")).trim());
            importSetting.setMemo(Util.null2String(rs.getString("memo")).trim());
            lsImportSetting.add(importSetting);
        }
        List<KQScheduleSignEntity> lsKQScheduleSignData = new ArrayList<>();
        KQScheduleSignEntity kqScheduleSignData = null;
        for (int i = 0; lsImportSetting != null && i < lsImportSetting.size(); i++) {
            DataSource ds = null;
            Connection conn = null;
            try {
                importSetting = lsImportSetting.get(i);
                String datasourceid = importSetting.getDatasourceid();
                String loginid = importSetting.getLoginid();
                String workcode = importSetting.getWorkcode();
                String lastname = importSetting.getLastname();
                String signdate = importSetting.getSigndate();
                String signtime = importSetting.getSigntime();
                String tablename = importSetting.getTablename();
                String clientaddress = importSetting.getClientaddress();
                String longitude = importSetting.getLongitude();
                String latitude = importSetting.getLatitude();
                String addr = importSetting.getAddr();
                String memo = importSetting.getMemo();

                ds = (DataSource) StaticObj.getServiceByFullname(("datasource." + datasourceid), DataSource.class);
                if (ds == null) continue;
                conn = ds.getConnection();
                conn.setAutoCommit(true);
                PreparedStatement pstmt = null;
                ResultSet resultSet = null;

                DateFormat df = new SimpleDateFormat("HH:mm:ss");

                sql = "select * from " + tablename + " where " + signdate + " >= '" + beginDate + "' and " + signdate + " < '" + endDate + "' order by " + signdate + (signtime.length() == 0 || signtime.equalsIgnoreCase(signdate) ? "" : (", " + signtime));

                if (!tablename.equals(this.pickUpTablename)) {
                    continue;
                }
                if (!"".equals(this.pickUpField)) {
                    sql = "select * from " + tablename + " where " + this.pickUpField + " >= '" + beginDate + "' and " + this.pickUpField + " < '" + endDate + "' order by " + this.pickUpField;
                    rs.writeLog("KQScheduleSignImportFromNewCapec-sql:" + sql);
                }
                pstmt = conn.prepareStatement(sql);
                resultSet = pstmt.executeQuery();
                List<String> noRepertSynData = new ArrayList<>();
                while (resultSet.next()) {
                    String tmpLoginid = "";
                    String tmpWorkcode = "";
                    String tmpLastname = "";
                    String tmpSigndate = "";
                    String tmpSigntime = "";
                    String tmpClientaddress = "";
                    String tmpLongitude = "";
                    String tmpLatitude = "";
                    String tmpAddr = "";
                    String tmpMemo = "";

                    if (loginid.length() > 0) tmpLoginid = Util.null2String(resultSet.getString(loginid)).trim();
                    if (workcode.length() > 0) tmpWorkcode = Util.null2String(resultSet.getString(workcode)).trim();
                    if (lastname.length() > 0) tmpLastname = Util.null2String(resultSet.getString(lastname)).trim();
                    if (signdate.length() > 0) tmpSigndate = Util.null2String(resultSet.getString(signdate)).trim();
                    if (clientaddress.length() > 0)
                        tmpClientaddress = Util.null2String(resultSet.getString(clientaddress));
                    if (longitude.length() > 0) tmpLongitude = Util.null2String(resultSet.getString(longitude)).trim();
                    if (latitude.length() > 0) tmpLatitude = Util.null2String(resultSet.getString(latitude)).trim();
                    if (addr.length() > 0) tmpAddr = Util.null2String(resultSet.getString(addr)).trim();
                    if (memo.length() > 0) tmpMemo = Util.null2String(resultSet.getString(memo)).trim();

                    if (signtime.length() > 0) {
                        tmpSigntime = Util.null2String(resultSet.getString(signtime)).trim();
                        //判断tmpSigntime格式 08:21:11 如果为长格式需要格式化
                        if (tmpSigntime.length() > 8) {
                            if (tmpSigntime.length() < 16) {//有遇到signtime格式为hh:mm:ss.0000的格式导致同步不成功
                                tmpSigntime = tmpSigntime.substring(0, 8);
                            } else {//比如上yyyy-mm-dd hh:mm的格式走原逻辑
                                tmpSigntime = df.format(Timestamp.valueOf(tmpSigntime));
                            }
                        } else if (tmpSigntime.length() < 8) {
                            //不带秒的情况  自动补齐
                            tmpSigntime += ":00";
                        }
                    } else {
                        tmpSigntime = "";
                    }

                    if (tmpSigndate.length() > 10) {
                        //如果时间为长格式，从signdate字段中格式化时间
                        if (tmpSigndate.length() == 16) {
                            //不带秒的情况  自动补齐
                            tmpSigntime += ":00";
                        }
                        if (tmpSigntime.length() == 0) {//以signtime字段为有限
                            tmpSigndate = tmpSigndate.length() > 19 ? tmpSigndate.substring(0, 19) : tmpSigndate;
                            tmpSigntime = df.format(Timestamp.valueOf(tmpSigndate));
                        }
                        tmpSigndate = Tools.formatDate(tmpSigndate, "yyyy-MM-dd");
                    }

                    //如果时间格式不带秒补齐
                    if (tmpSigntime.length() <= 5) {
                        tmpSigntime += ":00";
                    }

                    kqScheduleSignData = new KQScheduleSignEntity();
                    kqScheduleSignData.setLoginid(tmpLoginid);
                    kqScheduleSignData.setWorkcode(tmpWorkcode);
                    kqScheduleSignData.setLastname(tmpLastname);
                    kqScheduleSignData.setSigndate(tmpSigndate);
                    kqScheduleSignData.setSigntime(tmpSigntime);
                    kqScheduleSignData.setClientaddress(tmpClientaddress);
                    kqScheduleSignData.setLongitude(tmpLongitude);
                    kqScheduleSignData.setLatitude(tmpLatitude);
                    kqScheduleSignData.setAddr(tmpAddr);
                    kqScheduleSignData.setMemo(tmpMemo);
                    if (!"".equals(this.pickUpField)) {
                        String uploadDate = resultSet.getString(this.pickUpField);
                        if (uploadDate.length() > 10) {
                            uploadDate=uploadDate.substring(0,10);

                        }

                        kqScheduleSignData.setUploadDate(uploadDate);
                    }

                    lsKQScheduleSignData.add(kqScheduleSignData);
                }
                resultSet.close();
                pstmt.close();
            } catch (Exception e) {
                new BaseBean().writeLog(e);
            } finally {
                if (conn != null) conn.close();
            }
        }
        List<String> noRepertSynData = new ArrayList<>();
        for (int i = 0; lsKQScheduleSignData != null && i < lsKQScheduleSignData.size(); i++) {
            kqScheduleSignData = lsKQScheduleSignData.get(i);
            String tmpLoginid = kqScheduleSignData.getLoginid();
            String tmpWorkcode = kqScheduleSignData.getWorkcode();
            String tmpLastname = kqScheduleSignData.getLastname();
            String tmpSigndate = kqScheduleSignData.getSigndate();
            String tmpSigntime = kqScheduleSignData.getSigntime();
            String tmpClientaddress = kqScheduleSignData.getClientaddress();
            String tmpLongitude = kqScheduleSignData.getLongitude();
            String tmpLatitude = kqScheduleSignData.getLatitude();
            String tmpAddr = kqScheduleSignData.getAddr();
            String tmpMemo = kqScheduleSignData.getMemo();

            String uploadDate = kqScheduleSignData.getUploadDate();

            int userid = 0;
            if (Util.null2String(tmpLoginid).length() > 0) {
                userid = StringUtil.parseToInt(loginidMap.get(tmpLoginid), 0);
//                userid = getUserId(tmpLoginid, "loginid", this.userlanguage);
            }
            if (userid == 0 && Util.null2String(tmpWorkcode).length() > 0) {
                userid = StringUtil.parseToInt(workcodeMap.get(tmpWorkcode), 0);
//                userid = getUserId(tmpWorkcode, "workcode", this.userlanguage);
            }
            if (userid == 0 && Util.null2String(tmpLastname).length() > 0) {
                userid = StringUtil.parseToInt(lastnameMap.get(tmpLastname), 0);
//                userid = getUserId(tmpLastname, "lastname", this.userlanguage);
            }

            if (userid <= 0) {
                new BaseBean().writeLog("人员id未找到>>>>>>>>>>" + JSONObject.toJSONString(kqScheduleSignData));
                continue;
            }
            String dkParamData = userid + "#" + tmpSigndate + "#" + tmpSigntime;
            if (noRepertSynData.contains(dkParamData)) {
                continue;
            }
            noRepertSynData.add(dkParamData);
            params = new ArrayList<>();
            params.add(userid);
            params.add(1);
            params.add(tmpSigndate);
            params.add(tmpSigntime);
            params.add(tmpClientaddress);
            params.add(1);
            params.add(1);
            params.add("OutDataSourceSyn");
            params.add(tmpLongitude);
            params.add(tmpLatitude);
            params.add(tmpAddr);
            params.add(tmpMemo);
            params.add(uploadDate);
            lsParams.add(params);

            String formatData = userid + "|" + tmpSigndate;
            if (!"".equals(this.pickUpField)) {
                formatData += "|" + uploadDate;
            }
            if (!lsFormatData.contains(formatData)) {
                lsFormatData.add(formatData);
            }
        }

        Map<String, List<String>> overtimeMap = Maps.newHashMap();
        List<String> overtimeList = Lists.newArrayList();
        //刷新报表数据
        for (int i = 0; lsFormatData != null && i < lsFormatData.size(); i++) {
            formatParams = new ArrayList<>();
            String key = lsFormatData.get(i);//String formatData = userid + "|" + tmpSigndate;
            String[] formatData = Util.splitString(lsFormatData.get(i), "|");
            String date_1 = DateUtil.addDate(formatData[1], -1);
            formatParams.add(formatData[0]);
            formatParams.add(date_1);
            lsFormatParams.add(formatParams);

            formatParams = new ArrayList<>();
            formatParams.add(formatData[0]);
            formatParams.add(formatData[1]);
            lsFormatParams.add(formatParams);

            if (!keymap.contains(key)) {
                keymap.add(key);
                delParams = new ArrayList<>();
                delParams.add(formatData[0]);

                if (formatData.length >= 3) {
                    delParams.add(formatData[2]);
                } else {
                    delParams.add(formatData[1]);
                }
                lsDelParams.add(delParams);
            }

            String resourceId = formatData[0];
            String kqdate = formatData[1];
            if (overtimeMap.containsKey(resourceId)) {
                List<String> tmp_overtimeList = overtimeMap.get(resourceId);
                if (!tmp_overtimeList.contains(kqdate)) {
                    tmp_overtimeList.add(kqdate);
                }
            } else {
                if (!overtimeList.contains(kqdate)) {
                    overtimeList.add(kqdate);
                }
                overtimeMap.put(resourceId, overtimeList);
            }
        }

        //删除本次同步数据
        sql = " delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and signdate = ? ";
        if (!"".equals(this.pickUpField)) {
            sql = " delete from hrmschedulesign where signfrom='OutDataSourceSyn' and userid =? and " + this.pickUpField + " = ? ";
        }
        Console.log("批量删除sql:" + sql);
        Console.log("批量删除lsDelParams:" + lsDelParams.size());
        bRs.executeBatchSql(sql, lsDelParams);


        sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo) "
                + " values(?,?,?,?,?,?,?,?,?,?,?,?)";
        if (!"".equals(this.pickUpField)) {
            sql = " insert into HrmScheduleSign (userid, usertype, signdate, signtime, clientaddress, isincom, isimport, signfrom, longitude, latitude, addr,memo," + this.pickUpField + ") "
                    + " values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
        }
        bRs.executeBatchSql(sql, lsParams);

        new KQFormatBiz().format(lsFormatParams);

        //处理加班生成
        List<KQTaskBean> tasks = new ArrayList<>();
        for (Map.Entry<String, List<String>> mme : overtimeMap.entrySet()) {
            String resid = mme.getKey();
            List<String> overList = mme.getValue();
            for (String date : overList) {
                SplitActionUtil.pushOverTimeTasks(date, date, resid, tasks);
            }
        }
        if (!tasks.isEmpty()) {
            KQQueue.writeTasks(tasks);
        }
    }

    public Map<String, Map<String, String>> getUsers(int language) {
        RecordSet rs = new RecordSet();
        String sql = "select id,loginid,lastname,workcode from hrmresource where status in(0,1,2,3)";
        if (Util.isEnableMultiLang()) {
            if (rs.getDBType().equalsIgnoreCase("sqlserver")) {
                sql = "select id,loginid,ltrim(rtrim(dbo.convToMultiLang(ltrim(rtrim(lastname))," + language + "))) as lastname,workcode from hrmresource where status in(0,1,2,3)";
            } else {
                sql = "select id,loginid,ltrim(rtrim(convToMultiLang(ltrim(rtrim(lastname))," + language + "))) as lastname,workcode from hrmresource where status in(0,1,2,3)";
            }
        }

        Map<String, Map<String, String>> users = new HashMap<String, Map<String, String>>();
        rs.execute(sql);
        Map<String, String> loginidMap = new HashMap<String, String>();
        Map<String, String> lastnameMap = new HashMap<String, String>();
        Map<String, String> workcodeMap = new HashMap<String, String>();
        String resourceId = "", loginid = "", lastname = "", workcode = "";
        while (rs.next()) {
            if (StringUtil.isNull(resourceId = StringUtil.vString(rs.getString("id")))) continue;
            if (StringUtil.isNotNull(loginid = StringUtil.vString(rs.getString("loginid"))))
                loginidMap.put(loginid, resourceId);
            if (StringUtil.isNotNull(lastname = StringUtil.vString(rs.getString("lastname"))))
                lastnameMap.put(lastname, resourceId);
            if (StringUtil.isNotNull(workcode = StringUtil.vString(rs.getString("workcode"))))
                workcodeMap.put(workcode, resourceId);
        }
        users.put("loginidMap", loginidMap);
        users.put("lastnameMap", lastnameMap);
        users.put("workcodeMap", workcodeMap);
        return users;
    }


}
